#    Copyright 2024 Yan Mingshu <yms_hi@Outlook.com>
#
#    Licensed under the Apache License, Version 2.0 (the "License");
#    you may not use this file except in compliance with the License.
#    You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS,
#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#    See the License for the specific language governing permissions and
#    limitations under the License.
import fire
import semver
from loguru import logger
import pathlib
import os
import sys
from git import Repo
import json
import datetime
from hashlib import sha256

def getDir(f:str) -> [str]:
    match len(f):
        case 1:
            return ["1"]
        case 2:
            return ["2"]
        case 3:
            return ["3",f[0]]
        case _:
            return [f[:2],f[2:4]]

def getFileSha(f:str) -> str:
    s = sha256()
    with open(f,"rb") as f:
        for bb in iter(lambda: f.read(409600), b""):
            s.update(bb)
    return s.hexdigest()

class Cli:
    @staticmethod
    def init():
        iu = input("索引链接：")
        au = input("api链接：")
        with open(pathlib.Path(os.getcwd()).joinpath("info.json"), "a", encoding="utf-8") as f:
            logger.info("创建信息文件")
            f.write(json.dumps({"template": "", "base": {"api": iu, "index": au}}))

        logger.info("初始化索引")
        pathlib.Path(os.getcwd()).joinpath("index").mkdir()
        ir = Repo.init(path=pathlib.Path(os.getcwd()).joinpath("index"))
        ir.close()

        pathlib.Path(os.getcwd()).joinpath("api").mkdir()

    @staticmethod
    def info():
        print("A simple example to manage a static fuxo repo")

    @staticmethod
    def add_package(name:str):
        manifest = {"name":name,
                    "license": input("许可协议："),
                    "authors":input("作者，按;分隔：").split(";"),
                    "category":input("类型："),
                    "releases":[],
                    "update_time":datetime.datetime.now().isoformat(timespec="hours"),
                    "create_time":datetime.datetime.now().isoformat(timespec="hours")
                    }

        pathlib.Path(os.getcwd()).joinpath("api", name.lower()).mkdir()
        with open(pathlib.Path(os.getcwd()).joinpath("api",name.lower(),"info.json"),"w+",encoding="utf-8") as f:
            f.write(json.dumps(manifest))

    @staticmethod
    def add_version(package:str,version:str,source:str):
        semver.parse(version)
        if not pathlib.Path(os.getcwd()).joinpath("api", package.lower()).exists():
            logger.error("未找到该包")
        if not pathlib.Path(source).exists():
            logger.error("未找到源代码包")

        pathlib.Path(os.getcwd()).joinpath("api", package.lower(),version).mkdir()
        sum = getFileSha(source)

        pathlib.Path(os.getcwd()).joinpath("index", *getDir(package.lower())).mkdir(parents=True, exist_ok=True)
        with open(pathlib.Path(os.getcwd()).joinpath("index", *getDir(package.lower()),package.lower()),"a+",encoding="utf-8") as f:
            f.write(json.dumps({"name":package,"vers":"v"+version,"cksum":sum,"yanked":False,"v":1})+"\n")

        logger.info("创建索引")
        r = Repo(path=pathlib.Path(os.getcwd()).joinpath("index"))
        r.index.add(str(pathlib.Path(os.getcwd()).joinpath("index", *getDir(package.lower()), package.lower())))
        r.index.commit(f"Add {package} {version}")

        logger.info("信息添加至表单")
        m = json.load(open(pathlib.Path(os.getcwd()).joinpath("api", package.lower(), "info.json")))
        m["releases"].append({"v":version,"publish_time": datetime.datetime.now().isoformat(timespec="hours")})
        m["create_time"] = datetime.datetime.now().isoformat(timespec="hours")
        with open(pathlib.Path(os.getcwd()).joinpath("api", package.lower(), "info.json"), "w",encoding="utf-8") as f:
            f.write(json.dumps(m)+"\n")


        os.system("cp \"{}\" \"{}\"".format(source,pathlib.Path(os.getcwd()).joinpath("api", package.lower(),version,"source.fu")))


if __name__ == "__main__":
    fire.Fire(Cli)